import React, { useEffect, useRef, useState } from 'react';
import {
  World,
  Circle,
  Rectangle,
  Polygon,
  Line,
  GraphicObject,
} from '../World';
import './WorldCanvas.css';

interface WorldCanvasProps {
  width?: number;
  height?: number;
  gridSize?: number;
  gridVisible?: boolean;
  backgroundColor?: string;
}

const WorldCanvas: React.FC<WorldCanvasProps> = ({
  width = 800,
  height = 600,
  gridSize = 20,
  gridVisible = true,
  backgroundColor = '#f8f9fa',
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const worldRef = useRef<World | null>(null);
  const [selectedObjects, setSelectedObjects] = useState<string[]>([]);
  const [interactionMode, setInteractionMode] = useState<'select' | 'create'>(
    'select',
  );
  const [shapeType, setShapeType] = useState<
    'circle' | 'rectangle' | 'polygon' | 'line'
  >('circle');

  // 初始化World实例
  useEffect(() => {
    if (!canvasRef.current) return;

    const canvas = canvasRef.current;
    const world = new World(canvas, {
      gridSize,
      gridVisible,
      backgroundColor,
    });

    worldRef.current = world;
    world.initialize();

    // 添加一些示例图形
    const circle = new Circle(50, {
      position: { x: 100, y: 100 },
      rotation: 0,
      scale: { x: 1, y: 1 },
      anchor: { x: 0.5, y: 0.5 },
    });
    circle.style.fillColor = '#e74c3c';
    world.addObject(circle);

    const rectangle = new Rectangle(120, 80, {
      position: { x: 300, y: 150 },
      rotation: 0,
      scale: { x: 1, y: 1 },
      anchor: { x: 0.5, y: 0.5 },
    });
    rectangle.style.fillColor = '#4ecdc4';
    world.addObject(rectangle);

    const polygon = new Polygon(
      [
        { x: 500, y: 100 },
        { x: 600, y: 100 },
        { x: 650, y: 200 },
        { x: 550, y: 250 },
        { x: 450, y: 200 },
      ],
      {
        position: { x: 0, y: 0 },
        rotation: 0,
        scale: { x: 1, y: 1 },
        anchor: { x: 0.5, y: 0.5 },
      },
    );
    polygon.style.fillColor = '#45b7d1';
    world.addObject(polygon);

    const line = new Line(
      { x: 200, y: 300 },
      { x: 400, y: 350 },
      {
        position: { x: 0, y: 0 },
        rotation: 0,
        scale: { x: 1, y: 1 },
        anchor: { x: 0.5, y: 0.5 },
      },
    );
    line.style.strokeColor = '#96ceb4';
    line.style.strokeWidth = 3;
    world.addObject(line);

    // 监听选择变化
    world.on('selectionChanged', (event) => {
      const selected = event.selected.map((obj) => obj.id);
      setSelectedObjects(selected);
    });

    return () => {
      world.destroy();
    };
  }, [gridSize, gridVisible, backgroundColor]);

  // 创建新图形
  const createShape = (x: number, y: number) => {
    if (!worldRef.current || interactionMode !== 'create') return;

    let newShape: GraphicObject;

    switch (shapeType) {
      case 'circle':
        newShape = new Circle(30, {
          position: { x, y },
          rotation: 0,
          scale: { x: 1, y: 1 },
          anchor: { x: 0.5, y: 0.5 },
        });
        newShape.style.fillColor = getRandomColor();
        break;
      case 'rectangle':
        newShape = new Rectangle(60, 40, {
          position: { x, y },
          rotation: 0,
          scale: { x: 1, y: 1 },
          anchor: { x: 0.5, y: 0.5 },
        });
        newShape.style.fillColor = getRandomColor();
        break;
      case 'polygon':
        newShape = new Polygon(
          [
            { x: x - 30, y: y - 20 },
            { x: x + 30, y: y - 20 },
            { x: x + 40, y: y + 20 },
            { x: x, y: y + 30 },
            { x: x - 40, y: y + 20 },
          ],
          {
            position: { x: 0, y: 0 },
            rotation: 0,
            scale: { x: 1, y: 1 },
            anchor: { x: 0.5, y: 0.5 },
          },
        );
        newShape.style.fillColor = getRandomColor();
        break;
      case 'line':
        newShape = new Line(
          { x: x - 40, y: y },
          { x: x + 40, y: y },
          {
            position: { x: 0, y: 0 },
            rotation: 0,
            scale: { x: 1, y: 1 },
            anchor: { x: 0.5, y: 0.5 },
          },
        );
        newShape.style.strokeColor = getRandomColor();
        newShape.style.strokeWidth = 2;
        break;
    }

    if (newShape) {
      worldRef.current.addObject(newShape);
    }
  };

  // 处理Canvas点击事件
  const handleCanvasClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
    if (!worldRef.current) return;

    const rect = canvasRef.current!.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;

    if (interactionMode === 'create') {
      createShape(x, y);
    }
  };

  // 删除选中的对象
  const deleteSelected = () => {
    if (!worldRef.current) return;

    const world = worldRef.current;
    const selected = world.getSelectedObjects();

    selected.forEach((obj) => {
      world.removeObject(obj);
    });
  };

  // 清空所有对象
  const clearAll = () => {
    if (!worldRef.current) return;

    const world = worldRef.current;
    const objects = world.getObjects();

    objects.forEach((obj) => {
      world.removeObject(obj);
    });
  };

  // 生成随机颜色
  const getRandomColor = () => {
    const colors = [
      '#ff6b6b',
      '#4ecdc4',
      '#45b7d1',
      '#96ceb4',
      '#feca57',
      '#ff9ff3',
      '#54a0ff',
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  };

  return (
    <div className="world-canvas-container">
      <div className="toolbar">
        <div className="tool-group">
          <button
            type="button"
            className={interactionMode === 'select' ? 'active' : ''}
            onClick={() => setInteractionMode('select')}
          >
            🖱️ 选择
          </button>
          <button
            type="button"
            className={interactionMode === 'create' ? 'active' : ''}
            onClick={() => setInteractionMode('create')}
          >
            ➕ 创建
          </button>
        </div>

        <div className="tool-group">
          <select
            value={shapeType}
            onChange={(e) => setShapeType(e.target.value as any)}
            disabled={interactionMode !== 'create'}
          >
            <option value="circle">圆形</option>
            <option value="rectangle">矩形</option>
            <option value="polygon">多边形</option>
            <option value="line">线段</option>
          </select>
        </div>

        <div className="tool-group">
          <button
            type="button"
            onClick={deleteSelected}
            disabled={selectedObjects.length === 0}
          >
            🗑️ 删除选中
          </button>
          <button type="button" onClick={clearAll}>
            🧹 清空所有
          </button>
        </div>

        <div className="status">选中对象: {selectedObjects.length} 个</div>
      </div>

      <canvas
        ref={canvasRef}
        width={width}
        height={height}
        onClick={handleCanvasClick}
        className="world-canvas"
      />
    </div>
  );
};

export default WorldCanvas;
